package com.atguigu.dga.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class ThreadDemo {

    public static void main(String[] args) throws InterruptedException {
        Integer  nums[]= {1,2,3,4,5,6};

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10));

        List<Integer>  sqrList =  new ArrayList<>(); //现货列表
        List<CompletableFuture<Integer>>  futureList= new ArrayList<>(); //期货合约列表
        long startMs = System.currentTimeMillis();
        //求平方
        for (Integer num : nums) {
            //加入异步编排
            CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
                Integer sqr = num * num;
                try {
                     Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return sqr;
            },threadPoolExecutor);
            futureList.add(future);
        }
        sqrList= futureList.stream().map(future -> future.join()).collect(Collectors.toList());
        //截止时间
        long endMs = System.currentTimeMillis();
        System.out.println("(endMs-startMs) = " + (endMs-startMs));
        //求和
        Integer sum=0;
        for (Integer sqr : sqrList) {
            sum+=sqr;
        }
        System.out.println("sum = " + sum);


    }
}
